package com.keepers.repair.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.keepers.repair.R;
import com.keepers.repair.activity.BaseActivity;
import com.keepers.repair.adapter.NotificationAdapter;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.model.UserModel;
import com.keepers.repair.net.DataLoader;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.view.PullRecyclerView;
import com.keepers.repair.view.TitleBar;

/**
 * auth aboom
 * date 2018/10/22
 */
public class MsgFragment extends BaseFragment {

    private UserModel loginUserInfo;
    private NotificationAdapter notificationAdapter;
    private PullRecyclerView    recyclerView;
    private View                emptyView;

    private boolean      isImmersiveStatusBar;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            this.isImmersiveStatusBar = ((BaseActivity) context).isImmersiveStatusBar;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = ff(R.layout.fragment_msg);
        if (isImmersiveStatusBar) {
            f(view, R.id.status_bar).setVisibility(View.VISIBLE);
        }
        loginUserInfo = SpHelper.getLoginUserInfo();
        TitleBar titleBar = f(view, R.id.title_bar);
        titleBar.initializeHeaderNo("通知");
        recyclerView = f(view, R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        notificationAdapter = new NotificationAdapter(R.layout.item_notification);
        recyclerView.setOnRefreshListener(this::refreshList);
        recyclerView.setAdapter(notificationAdapter);
        emptyView = f(view, R.id.empty_view);
        refreshList();
        return view;
    }

    private void refreshList() {
        recyclerView.showRefresh();
        rxHelper.pend(DataLoader.getNotification(loginUserInfo.GroupGid, loginUserInfo.Gid, notificationsModel -> {
            recyclerView.loadComplete(true);
            if (notificationsModel == null) {
                AlertToast.show("网络错误");
                return;
            }
            emptyView.setVisibility(notificationsModel.Notice.size() == 0 ? View.VISIBLE : View.GONE);
            notificationAdapter.setNewData(notificationsModel.Notice);
        }));
    }
}
